#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
阿里宝宝电商平台 - 快速启动脚本（Python版本）
可以在macOS上双击运行
"""

import os
import sys
import subprocess
import signal

def check_port(port):
    """检查端口是否被占用"""
    try:
        result = subprocess.run(['lsof', '-ti', f':{port}'], 
                              capture_output=True, text=True)
        if result.stdout.strip():
            return True, result.stdout.strip().split('\n')[0]
        return False, None
    except:
        return False, None

def kill_process(pid):
    """终止进程"""
    try:
        os.kill(int(pid), signal.SIGKILL)
        return True
    except:
        return False

def check_dependencies():
    """检查依赖"""
    try:
        import flask
        import flask_cors
        return True
    except ImportError:
        return False

def main():
    print("=" * 60)
    print("阿里宝宝电商平台 - Web服务器启动\nAli Bao Bao Ecommerce Platform - Web Server Starting")
    print("=" * 60)
    print()
    
    # 获取脚本所在目录
    script_dir = os.path.dirname(os.path.abspath(__file__))
    os.chdir(script_dir)
    
    # 检查Python版本
    print(f"✓ Python版本: {sys.version}\nPython Version: {sys.version}")
    print()
    
    # 检查依赖
    if not check_dependencies():
        print("⚠️  正在安装依赖包...\nInstalling required dependencies...")
        try:
            subprocess.run([sys.executable, '-m', 'pip', 'install', 
                          'flask', 'flask-cors', 'requests', '-q'], 
                         check=True)
            print("✓ 依赖安装完成\nDependencies installed successfully.")
        except:
            print("❌ 依赖安装失败，请手动运行: pip3 install flask flask-cors requests\nDependency installation failed. Please run manually: pip3 install flask flask-cors requests")
            input("\n按回车键退出...\nPress Enter to exit...")
            return
    else:
        print("✓ 依赖包已安装\nDependencies already installed.")
    print()
    
    # 检查端口
    port = 8000
    is_occupied, pid = check_port(port)
    if is_occupied:
        print(f"⚠️  端口 {port} 已被占用（进程ID: {pid}）\nPort {port} is occupied (PID: {pid})")
        print("正在关闭占用端口的进程...\nTerminating the process occupying the port...")
        if kill_process(pid):
            print("✓ 端口已释放\nPort released.")
        else:
            print("⚠️  无法自动关闭，请手动关闭或使用其他端口\nUnable to close automatically. Please close manually or use a different port.")
            input("\n按回车键继续...\nPress Enter to continue...")
        print()
    
    # 启动服务器
    print("=" * 60)
    print("正在启动Web服务器...\nStarting Web Server...")
    print("=" * 60)
    print(f"服务器地址: http://localhost:{port}\nServer address: http://localhost:{port}")
    print(f"主页: http://localhost:{port}/index.html\nHome page: http://localhost:{port}/index.html")
    print()
    print("提示: 按 Ctrl+C 停止服务器\nTip: Press Ctrl+C to stop the server")
    print("=" * 60)
    print()
    
    try:
        # 启动服务器
        server_path = os.path.abspath(os.path.join(script_dir, '..', 'ali_bao_bao', 'web_frontend', 'server-simple.py'))

# 切换到 server-simple.py 所在目录，避免静态资源/相对路径问题
        os.chdir(os.path.dirname(server_path))

# 启动服务器
        subprocess.run([sys.executable, server_path])
    except KeyboardInterrupt:
        print("\n\n服务器已停止\nServer stopped.")
    except Exception as e:
        print(f"\n❌ 启动失败: {e}\nFailed to start: {e}")
        input("\n按回车键退出...\nPress Enter to exit...")

if __name__ == '__main__':
    main()
